//初始化在线文本编辑器
const E = window.wangEditor
const editor = new E('#div1')
const $text1 = $('#text1')
editor.config.onchange = function (html) {
    // 第二步，监控变化，同步更新到 textarea
    $text1.val(html)
}
//配置上传的文件以base64格式保存在本地
editor.config.uploadImgShowBase64 = true
editor.create()
//赋值给editor
//editor.txt.html($text1.val());

//表单提交验证
layui.use(['form', 'layer', 'upload'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;
    //文件上传
    //执行实例
    upload.render({
        elem: '#test1', //绑定元素
        url: '/upload', //上传接口
        accept: 'images',
        done: function (res) {
            //上传完毕回调
            if(res.status==200){
                //显示预览图片
                $('#uploadFileView').attr('src',res.data).show();
                //隐藏域赋值
                $('#img_url').val(res.data)
            }
        }
    });

    //自定义验证规则
    form.verify({
        img_url: function (value) {
            if (value.length <= 0) {
                return '必须要上传文件';
            }
        }
    });

    //监听提交
    form.on('submit(demo1)', function (data) {
        var formData = data.field;
        //去掉多余的属性file
        _.unset(formData, 'file');
        //发送ajax请求
        $.post('/admin/news',formData,function(res){
             if(res.status==201){
                 layer.msg('添加成功',{icon:6,time:1000},function(){
                      location.href='/admin/news'
                 })
             }else{
                 layer.msg(res.msg, {
                     icon: 5,
                     time: 3000
                 }, function () {
                     location.href = '/admin/news/create'
                 })
             }
        });

        return false;
    });


});